<template>
	<view class="container">
		<ua-markdown :source="Example1" show-line="false" />
  </view>
</template>
<script setup>
  import { ref } from 'vue'

  import { onShow, onLoad, onHide, onUnload, onShareAppMessage } from '@dcloudio/uni-app'
  const Example1 = ref('')
  const interviewId = ref('')
  let requestTask = {}




  onLoad((e) => {
    Example1.value = ""
    interviewId.value = e.id || ''
  })

 
  let bufferCache = new Uint8Array(0); // 缓存不完整的数据块

  // 从 ArrayBuffer 正确解码文本
  const  arrayBufferToString = (arrayBuffer, encoding = 'utf-8') => {
    const uint8Array = new Uint8Array(arrayBuffer);
    
    // 优先使用 TextDecoder
    if (typeof TextDecoder !== 'undefined') {
      return new TextDecoder(encoding).decode(uint8Array);
    }
    
    // 降级方案（手动 UTF-8 解码）
    return utf8ArrayToString(uint8Array);
  }



  const utf8ArrayToString = (uint8Array) => {
      let str = '';
      let i = 0;
      while (i < uint8Array.length) {
        const byte1 = uint8Array[i++];
        if (byte1 < 0x80) {
          // 1 字节字符（ASCII）
          str += String.fromCharCode(byte1);
        } else if (byte1 >= 0xC0 && byte1 < 0xE0) {
          // 2 字节字符（如中文）
          const byte2 = uint8Array[i++];
          str += String.fromCharCode(((byte1 & 0x1F) << 6) | (byte2 & 0x3F));
        } else if (byte1 >= 0xE0 && byte1 < 0xF0) {
          // 3 字节字符（如部分 Emoji）
          const byte2 = uint8Array[i++];
          const byte3 = uint8Array[i++];
          str += String.fromCharCode(
            ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F)
          );
        } else {
          // 4 字节字符（需要代理对，这里简化处理）
          str += '�'; // 替换为占位符
        }
      }
      return str;
    }


  const getSSe = () => {
      uni.showLoading()
      const data = {
        interview_id: interviewId.value
      } 
      requestTask = uni.request({
        url: 'https://api.bytesbay.cn/bole/interview/generateReport',
        method: 'POST',
        header: {
          Accept: 'text/event-stream',
          Token: uni.getStorageSync('bytesbayToken')
        },
        data,
        enableChunked: true,
        responseType: 'arraybuffer',
        success: (res) => {
          console.log('Data received 数据接受完毕:', res.data)
        },
        fail: (error) => {
          console.log('打印***error 错误处理', error)
        },
        complete: (complete) => { 
          console.log('打印***complete 完成接收', complete)
        }
      })

      let lastText = ''
      requestTask.onChunkReceived((res) => { 
        uni.hideLoading()
        // processStreamData(res.data)z
        // 第一步：获取 字符串 数组
        const uint8Array = arrayBufferToString(res.data);
        let text = lastText + uint8Array;
        lastText = '';
        let arr = text.split('\n\n').filter(Boolean)
        let lastIndex = arr.length - 1

        console.log('-------------', arr)
        // 第二步：是否可以直接进行解析
        let isCanResolve = arr.every(item => item.substring(11))
        // console.log('打印***isCanResolve', isCanResolve)
        // try {
        //   let isCanResolve = arr.every(item => JSON.parse(item.substring(11)))
        //   console.log('打印***isCanResolve', isCanResolve)
        // } catch (error) {
        //   // 如果报错截取最后一项
        //   lastText = arr[lastIndex]
        //   arr = arr.filter((_, i) => i !== lastIndex)
        //   console.log('打印***error', error)
        // }

        // 处理数据块
        if (arr.length) {
          try {
            arr.forEach(msg => {
              const jsonStr = msg.replace("data: ", ""); // 去掉 'data:data: ' 前缀
              // const data = JSON.parse(jsonStr);
              // const existingMessageIndex = this.dialogueList.findIndex(item => item === msgObj);
              Example1.value += jsonStr;
              // switch (data.event) {
              //   case 'message': {
              //     // 查找是否存在相同ID的消息
              //     Example1.value += data.answer;
              //     // this.dialogueList[existingMessageIndex].answer += data.answer;
              //     break;
              //   }
              //   case 'message_end':
              //     // 消息结束
              //     // this.dialogueList[existingMessageIndex].isDone = true;
              //     break;
              // }
            });
          } catch (error) {
            console.error('解析数据失败:', error);
          }
        }
      });


    // const requestTask = uni.request({
    //   url: 'https://api.bytesbay.cn/bole/interview/generateReport',
    //   method: 'POST',
    //   header: {
    //     Accept: 'text/event-stream',
    //     Token: uni.getStorageSync('bytesbayToken')
    //   },
    //   data:{
    //     interview_id: interviewId.value
    //   },
    //   enableChunked: true,
    //   // responseType: 'arraybuffer',
    //   success: (res) => {
    //     console.log('Data received 数据接受完毕:', res.data)
    //   },
    //   fail: (error) => {
    //     console.log('打印***error 错误处理', error)
    //   },
    //   complete: (complete) => {
    //     console.log('打印***complete 完成接收', complete)
    //   }
    // })

    // requestTask.onChunkReceived((res)=>{
    //   console.log('------onChunkReceived------------', res)
    //   // 处理数据
    // })
  }


  // 处理流式数据
const processStreamData = (arrayBuffer) => {
  // 合并缓存（处理分包情况）
  const newData = new Uint8Array(arrayBuffer);
  const mergedData = new Uint8Array(bufferCache.length + newData.length);
  mergedData.set(bufferCache, 0);
  mergedData.set(newData, bufferCache.length);

  // 尝试按 \n\n 分割事件（SSE 标准格式）
  const textDecoder = new TextDecoder('utf-8');
  const dataStr = textDecoder.decode(mergedData);
  const events = dataStr.split('\n\n');

  // 最后一个事件可能是残缺的，放回缓存
  bufferCache = new Uint8Array(
    textDecoder.encode(events.pop() || '')
  );

  // 处理完整事件
  events.forEach(event => {
    if (event.trim()) {
      console.log('解析到 SSE 事件:', parseSSEEvent(event));
    }
  });
}


// 解析 SSE 事件格式（如 "data: {...}\nid: 123"）
const parseSSEEvent = (rawEvent) => {
  const lines = rawEvent.split('\n');
  const result = {};
  lines.forEach(line => {
    const [key, value] = line.split(': ');
    if (key && value) result[key] = value;
  });
  return result;
}

  onUnload(() => {
    requestTask && requestTask.abort()
  })


  onShareAppMessage(() => {
    return {
      title: '查看报告',
      path: "/pages/webauth/webauth?cb="+ encodeURIComponent('/pages/markdown/index?id='+ interviewId.value)
    }
  })


  onShow(() => {
    console.log('0-----------getSSe--------------')
    console.log("/pages/webauth/webauth?cb="+ encodeURIComponent('/pages/markdown/index?id='+ interviewId.value))
    getSSe()
  })
</script>
<style lang="scss">
  .container{
    padding: 40rpx 32rpx 100rpx 32rpx
  }
</style>